import threading
import multiprocessing

import time

def compute(start, end):
    sum = 0
    for i in range(start, end):
        sum += i

def compute2(start, end):
    sum = 0
    for i in range(start, end):
        sum += i

def io():
    time.sleep(10)

def use_thread_compute():
    interval = 20000000
    threads = []
    for i in range(0, 5):
        threads.append(threading.Thread(target=compute, args=(i*interval, (i+1)*interval,)))
    for t in threads:
        t.start()
    for t in threads:
        t.join()

def use_process_compute():
    interval = 20000000
    processes = []
    for i in range(0, 5):
        # processes.append(multiprocessing.Process(target=compute2, args=(100, 200,)))
        processes.append(multiprocessing.Process(target=compute2, args=(i*interval, (i+1)*interval,)))
    for t in processes:
        t.start()
    for t in processes:
        t.join()

def use_thread_io():
    threads = []
    for i in range(0, 5):
        threads.append(threading.Thread(target=io))
    for t in threads:
        t.start()
    for t in threads:
        t.join()

def use_process_io():
    processes = []
    for i in range(0, 5):
        processes.append(multiprocessing.Process(target=io))
    for t in processes:
        t.start()
    for t in processes:
        t.join()

if __name__ == "__main__":
    start = time.time()
    use_thread_compute()
    end = time.time()
    print("compute thread time use: %s" % (end - start))
    start = time.time()
    use_process_compute()
    end = time.time()
    print("compute process time use: %s" % (end - start))
    start = time.time()
    use_thread_io()
    end = time.time()
    print("compute thread time use: %s" % (end - start))
    start = time.time()
    use_process_io()
    end = time.time()
    print("compute process time use: %s" % (end - start))
    print("""
    
    从结果我们可以看到，计算密集型任务，使用多进程比多线程快了3.1s左右。这是因为python有GIL（全局解释器锁），这个锁的作用就是在线程执行前，必须获取到这个锁，导致同一时间只能有一个python线程在执行，python的多线程是一种伪并行。

而多进程不受GIL的限制，多个进程是并行执行，所以计算速度就比多线程快了很多。

而对于io密集型任务，等待io的时间无法做其他事情，大家都在等待，进程切换比线程切换更耗时，结果就是io密集型任务中，使用多进程比多线程还慢了0.1s左右。
    """)